package com.iwunu.gateway.service.impl;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.iwunu.gateway.cache.RedisService;
import com.iwunu.gateway.entity.CmdIssued;
import com.iwunu.gateway.entity.ImageMongo;
import com.iwunu.gateway.service.CmdIssuedMongodbService;
import com.iwunu.gateway.util.PitNumUtil;
import com.iwunu.gateway.vo.CmdIssuedVo;
import com.iwunu.gateway.vo.UpdateCmdIssuedVo;
import com.iwunu.iot.common.constant.ClientOpenTypeEnum;
import com.iwunu.iot.common.util.DateUtil;
import com.mongodb.client.result.UpdateResult;

@Component
public class CmdIssuedMongodbServiceImpl implements CmdIssuedMongodbService {
	@Autowired
	private RedisService redisService;
	@Resource
	private MongoTemplate mongoTemplate;
	public String saveSendImageData(List<CmdIssuedVo> cmdissueds, String userId, String clientId, Integer type,Integer role) {
		List<CmdIssued> cmdIssuedList = new ArrayList<CmdIssued>();
		List<CmdIssued> cmds = this.getSendCmd(clientId, type);
		List<Integer> pitNums = PitNumUtil.getCmdPitNum(cmds,cmdissueds.size());
		CmdIssued cmdIssued = new CmdIssued();
		 if(pitNums.get(0)>=100) {
			 return "";
		 }
		String result = StringUtils.join(pitNums,",");
		for (CmdIssuedVo vo : cmdissueds) {
			cmdIssued.setClientId(clientId);
			cmdIssued.setData(vo.getData());
			cmdIssued.setEndTime(vo.getEndTime());
			cmdIssued.setUserId(userId);
			cmdIssued.setFlDeviceId(clientId);
			cmdIssued.setStartTime(vo.getStartTime());
			cmdIssued.setSucc(false);
			cmdIssued.setValid(true);
			cmdIssued.setStatus(0);
			cmdIssued.setType(type);
			cmdIssued.setRole(role);
			cmdIssued.setSerialNumber(clientId +StringUtils.leftPad(pitNums.get(0)+"", 3, "0")+type);
			if(vo.getPitNum()!=null) {
				cmdIssued.setPitNum(vo.getPitNum());
				result = vo.getPitNum().toString();
			}else {
				cmdIssued.setPitNum(pitNums.get(0));				
				pitNums.remove(0);
			}
			
			cmdIssuedList.add(cmdIssued);
			if(type==10) {
				cmdIssued.setPitNum(0);	//测试
			}
			redisService.rightPush(clientId + "##_"+type, JSONObject.toJSONString(cmdIssued));
			List<String> sendData = redisService.getList(clientId + "##_"+type);
			for(String data:sendData) {
				System.out.println("redis addPwd+++++++++++++++:"+data);
			}
			
		}
		try {
			mongoTemplate.insertAll(cmdIssuedList);
		} catch (Exception e) {
			redisService.del(clientId + type);
			e.printStackTrace();
		}
		return result;
	}
	public String saveSendAdvertData(List<CmdIssuedVo> cmdissueds, String userId, String clientId, Integer type,Integer role) {
		List<CmdIssued> cmdIssuedList = new ArrayList<CmdIssued>();
		List<CmdIssued> cmds = this.getSendCmd(clientId, type);
		List<Integer> pitNums = PitNumUtil.getCmdPitNum(cmds,cmdissueds.size());
		CmdIssued cmdIssued = new CmdIssued();
		String key  =  clientId+ClientOpenTypeEnum.ADVERT.getData();  ;
		 if(pitNums.get(0)>=3) {
			 return "";
		 }
		 String result = StringUtils.join(pitNums,",");
		for (CmdIssuedVo vo : cmdissueds) {
			CmdIssued cmd = this.getSendCmdByData(clientId,userId, type, vo.getData());
			if(cmd!=null && vo.getEndTime().compareTo(cmd.getEndTime())<0) {
				continue;
			}else if(cmd!=null && vo.getEndTime().compareTo(cmd.getEndTime())>0) {
				redisService.rightPush(key, cmd.getPitNum().toString());
			}
			cmdIssued.setClientId(clientId);
			cmdIssued.setData(vo.getData());
			cmdIssued.setEndTime(vo.getEndTime());
			cmdIssued.setUserId(userId);
			cmdIssued.setFlDeviceId(clientId);
			cmdIssued.setStartTime(vo.getStartTime());
			cmdIssued.setSucc(false);
			cmdIssued.setValid(true);
			cmdIssued.setStatus(0);
			cmdIssued.setType(type);
			cmdIssued.setRole(role);
			cmdIssued.setPitNum(pitNums.get(0));				
			cmdIssued.setSerialNumber(clientId +StringUtils.leftPad(pitNums.get(0)+"", 3, "0")+type);
			pitNums.remove(0);
			cmdIssuedList.add(cmdIssued);
			redisService.del(clientId + "##_"+type);
			redisService.rightPush(clientId + "##_"+type, JSONObject.toJSONString(cmdIssued));
		}
		try {
			mongoTemplate.insertAll(cmdIssuedList);
		} catch (Exception e) {
			redisService.del(clientId + type);
			e.printStackTrace();
		}
		return result;
	}
	public Integer saveBleSendImageData(CmdIssuedVo cmdissueds, String clientId, Integer type) {
		List<CmdIssued> cmds = this.getSendCmd(clientId, type);
		List<Integer> pitNums = PitNumUtil.getCmdPitNum(cmds,1);
		CmdIssued cmdIssued = new CmdIssued();
			if(pitNums.get(0)>=100) {
			 return 0;
			}
			cmdIssued.setClientId(clientId);
			cmdIssued.setData(clientId +type);
			cmdIssued.setEndTime(cmdissueds.getEndTime());
			cmdIssued.setUserId(null);
			cmdIssued.setFlDeviceId(clientId);
			cmdIssued.setStartTime(cmdissueds.getStartTime());
			cmdIssued.setSucc(false);
			cmdIssued.setValid(false);
			cmdIssued.setType(type);
			cmdIssued.setRole(100);
			cmdIssued.setRemark(cmdissueds.getRemark());
			cmdIssued.setPitNum(pitNums.get(0));
			cmdIssued.setSerialNumber(clientId +StringUtils.leftPad(pitNums.get(0)+"", 3, "0")+type);
		try {
			mongoTemplate.insert(cmdIssued);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return pitNums.get(0);
	}
	
	public void updateBleCmd(CmdIssued cmdIssued) {
		try {
			Query query = new Query(Criteria.where("serialNumber").is(cmdIssued.getSerialNumber()).and("pitNum").is(cmdIssued.getPitNum()).and("type").is(cmdIssued.getType()).and("isSucc").is(false));
			Update update = new Update();
			update.set("data", cmdIssued.getData());
			update.set("remark", cmdIssued.getRemark());
			update.set("role", cmdIssued.getRole());
			update.set("userId", cmdIssued.getUserId());
			update.set("isValid",true);
			update.set("isSucc",true);
			update.set("status",1);
//			System.out.println("updateBleCmd Update:"+update.toString());
			mongoTemplate.findAndModify(query, update, CmdIssued.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public List<CmdIssued>  getSendCmd(String clientId, String type) {
		Query query = new Query(Criteria.where("clientId").is(clientId).and("type").is(type).and("endTime").gte(DateUtil.nowDateTime()));
		List<CmdIssued> cmdIssueds = mongoTemplate.find(query, CmdIssued.class);
		return cmdIssueds;
	}
	
	public List<CmdIssued>  getSendCmdByUser(Integer userId,String clientId) {
		Query query = new Query(Criteria.where("userId").is(userId).and("clientId").is(clientId).and("isSucc").is(true).and("endTime").gte(DateUtil.nowDateTime()));
		List<CmdIssued> cmdIssueds = mongoTemplate.find(query, CmdIssued.class);
		return cmdIssueds;
	}
	
	public List<CmdIssued>  getUserSendCmd(Integer userId, String clientId, Integer type) {
		Query query = new Query(Criteria.where("clientId").is(clientId).and("userId").is(userId).and("type").is(type).and("endTime").gte(DateUtil.nowDateTime()));
		List<CmdIssued> cmdIssueds = mongoTemplate.find(query, CmdIssued.class);
		return cmdIssueds;
	}
	
	public void removeCmd(String clientId, Integer pitNum,Integer type) {
		Query query = new Query(Criteria.where("clientId").is(clientId).and("pitNum").is(pitNum).and("type").is(type));
		 mongoTemplate.remove(query, CmdIssued.class);
	}
	@Override
	public void updateCmd(String clientId, Integer pitNum,Integer type) {
		Query query = new Query(Criteria.where("clientId").is(clientId).and("pitNum").is(pitNum).and("type").is(type));
		Update update = Update.update("isValid", false).set("status", 3);
		mongoTemplate.findAndModify(query, update, CmdIssued.class);
	}
	@Override
	public long updateStatus(String clientId) {
		Update update = Update.update("status", 2);
		Query query = new Query(Criteria.where("clientId").is(clientId).and("status").is(-1));
		UpdateResult wr = mongoTemplate.updateMulti(query, update, CmdIssued.class);
		return wr.getMatchedCount();
	}

	
	public List<CmdIssued>  getSendCmdByOwner(String clientId,Integer userId) {
		Query query = new Query(Criteria.where("clientId").is(clientId).and("userId").is(userId));
		List<CmdIssued> cmdIssueds = mongoTemplate.find(query, CmdIssued.class);
		return cmdIssueds;
	}
	
	public List<CmdIssued>  getSendCmd(String clientId,Integer type) {
		Query query = new Query(Criteria.where("clientId").is(clientId).and("type").is(type).and("endTime").gte(DateUtil.nowDateTime()));
		List<CmdIssued> cmdIssueds = mongoTemplate.find(query, CmdIssued.class);
		return cmdIssueds;
	}
	public CmdIssued  getSendCmdByData(String clientId,Integer userId,Integer type,String data) {
		Query query = new Query(Criteria.where("clientId").is(clientId).and("userId").is(userId).and("type").is(type).and("data").is(data));
		CmdIssued cmdIssued = mongoTemplate.findOne(query, CmdIssued.class);
		return cmdIssued;
	}
	public CmdIssued  getSendCmdByData(String clientId,String userId,Integer type,String data) {
		Query query = new Query(Criteria.where("clientId").is(clientId).and("userId").is(userId).and("type").is(type).and("data").is(data));
		CmdIssued cmdIssued = mongoTemplate.findOne(query, CmdIssued.class);
		return cmdIssued;
	}
	public void  removeCmdData(String clientId,Integer userId,Integer type,String data) {
		Query query = new Query(Criteria.where("clientId").is(clientId).and("userId").is(userId).and("type").is(type).and("data").is(data));
		mongoTemplate.remove(query, CmdIssued.class);
	}
	public CmdIssued  getExitBleSendCmdByData(String clientId,Integer type,String data) {
		Query query = new Query(Criteria.where("clientId").is(clientId).and("type").is(type).and("data").is(data).and("isSucc").is(true));
		CmdIssued cmdIssued = mongoTemplate.findOne(query, CmdIssued.class);
		return cmdIssued;
	}	
	public CmdIssued  getBleSendCmdByData(String clientId,Integer type,Integer pitNum) {
//		System.out.println("getBleSendCmdByData clientId --->"+clientId+";type:type"+"---->pitNum:"+pitNum);
		Query query = new Query(Criteria.where("clientId").is(clientId).and("type").is(type).and("pitNum").is(pitNum).and("role").is(100)).limit(1);
		CmdIssued cmdIssued = mongoTemplate.findOne(query, CmdIssued.class);
		return cmdIssued;
	}
	@Override
	public void removeCmdByDeviceId(String clientId) {
//		System.out.println("removeCmdByDeviceId:clientId --->"+clientId);
		Query query = new Query(Criteria.where("clientId").is(clientId));
		 mongoTemplate.remove(query, CmdIssued.class);
	}
	public static void main(String[] args) {
		String time = "2021-06-10 00:00:00";
		String endTime = "2021-06-10 00:00:12";
		System.out.println(endTime.compareTo(time));
		List list = new ArrayList<Integer>();
		list.add(1);
		System.out.println(StringUtils.join(list,","));
	}
}
